import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000, // request timeout
  headers: {
    'Content-Type': 'application/json'
  },
  config: {
    useLoading: true
  }
})

// request interceptor
service.interceptors.request.use(config => {
  
  config.config.useLoading && store.dispatch('setPageLoading', true)

  if (store.getters.userInfo) {
    config.headers['Authorization'] = store.getters.userInfo.openid // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
  }

  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  return Promise.reject(error)
})

service.interceptors.response.use(response => {

  store.dispatch('setPageLoading', false)

  return response
}, error => {
  store.dispatch('setPageLoading', false)

  console.log(error.response) // for debug

  if (error.response.status === 404) {
    router.push('/404')
  }

  // 如果是未认证用户（没有openid）,则直接放回首页
  if (error.response.status === 401) {
    Vue.$vux.alert.show({
      content: i18n.t('loginFailed', err),
      buttonText: i18n.t("tryAgainByClick"),
      onHide: () => {
        window.location.href = window.location.origin
      }
    })
  }

  return Promise.reject(error)
})

export default service
